﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using TTSDAL;
using System.Drawing;
using System.IO;
using System.Text;
public partial class QualityControl_T0001996_SummaryReport : System.Web.UI.Page
{
    private T0001996_SummaryReport _T0001996_SummaryReport;
    private int id { get { return Convert.ToInt32(ViewState["id"].ToString()); } set { ViewState["id"] = value; } }
    private string startSN { get { return ViewState["startSN"].ToString(); } set { ViewState["startSN"] = value; } }
    private string endSN { get { return ViewState["endSN"].ToString(); } set { ViewState["endSN"] = value; } }
    private string testType { get { return ViewState["testType"].ToString(); } set { ViewState["testType"] = value; } }

    private string clickEventArgs { get { return ViewState["clickEventArgs"] == null ? "" : ViewState["clickEventArgs"].ToString(); } set { ViewState["clickEventArgs"] = value; } }//定义点击的是哪个键

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.GridView1.PagerSettings.Visible = false;//隐藏自带的分页
            ViewState["SortCPK"] = "CpkValue";//排序的字段
            ViewState["SortUnitsFailed"] = "FailedCount";//排序的字段
            ViewState["SortFailedRate"] = "FailedRate";//排序的字段
            ViewState["CPKDire"] = "ASC";//来初始化登录时按照什么排序，是倒序还是正序
            ViewState["UnitsFailedDire"] = "ASC";//来初始化登录时按照什么排序，是倒序还是正序
            ViewState["FailedRateDire"] = "ASC";
            // BindSort();
        }
    }
    public QualityControl_T0001996_SummaryReport()
    {
        _T0001996_SummaryReport = new T0001996_SummaryReport();
    }
    protected void Check_Click(object sender, EventArgs e)
    {
        string startSNTek = this.TextBox1.Text.Trim();
        string endSNTek = this.TextBox2.Text.Trim();
        testType = GetTypeValue(this.DropDownList1.SelectedValue);
        if (!string.IsNullOrEmpty(startSNTek))
        {
            startSN = startSNTek.Substring(startSNTek.Length - 9, 9);
        }
        else
        {
            this.TextBox1.Focus();
            return;
        }
        if (!string.IsNullOrEmpty(endSNTek))
        {
            endSN = endSNTek.Substring(endSNTek.Length - 9, 9);
        }
        else
        {
            this.TextBox2.Focus();
            return;
        }
        if (startSNTek == endSNTek)
        {
            this.TextBox2.Text = "";
            this.TextBox2.Focus();
            return;
        }
        Session["startSN"] = startSN;
        Session["endSN"] = endSN;
        Session["testType"] = testType;
        //this.GridView1.Visible = true;
        BindSort();
        this.ExportToExcel.Visible = true;
    }
    public void BindSort()
    {
        if (testType == "FirstTest")
        {

            DataSet DsF = _T0001996_SummaryReport.GetFirstTestDataSet("fds", startSN, endSN);
            if ((DsF.Tables["fds"].Rows[0]["Column1"]) is DBNull)
            {
                return;
            }
        }
        DataSet ds = _T0001996_SummaryReport.GetSummaryDataSet("myds", startSN, endSN, testType);
        if ((ds.Tables["myds"].Rows[0]["CpkValue"]) is DBNull)
        {
            return;
        }
        else
        {
            DataView dv = ds.Tables["myds"].DefaultView;
            //string sortCPK = (string)ViewState["SortCPK"] + " " + (string)ViewState["CPKDire"];
            //string sortUnitsFailed = (string)ViewState["SortUnitsFailed"] + " " + (string)ViewState["UnitsFailedDire"];
            //string sortFailedRate = (string)ViewState["SortFailedRate"] + " " + (string)ViewState["FailedRateDire"];
            //dv.Sort = sortCPK + "," + sortUnitsFailed + "," + sortFailedRate;
            GridView1.DataSource = dv;
            GridView1.DataBind();
            this.ddlCurrentPage.Items.Clear();
            for (int i = 1; i <= this.GridView1.PageCount; i++)
            {
                this.ddlCurrentPage.Items.Add(i.ToString());
            }
            this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
        }
    }
    public void BindSort(string _sortName, string _sortDire)
    {
        DataSet ds = _T0001996_SummaryReport.GetSummaryDataSet("mys", startSN, endSN, testType);
        DataView dv = ds.Tables["mys"].DefaultView;
        string sortCPK = (string)ViewState[_sortName] + " " + (string)ViewState[_sortDire];
        dv.Sort = sortCPK;
        GridView1.DataSource = dv;
        GridView1.DataBind();
        this.ddlCurrentPage.Items.Clear();
        for (int i = 1; i <= this.GridView1.PageCount; i++)
        {
            this.ddlCurrentPage.Items.Add(i.ToString());
        }
        this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
    }

    private string GetTypeValue(string _DropDownListSelected)
    {
        if (_DropDownListSelected == "第一次测试CPK")
        {
            return "FirstTest";
        }
        else
        {
            return "FinalTest";
        }
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // string sPage = e.SortExpression;
        clickEventArgs = e.SortExpression;
        LoadGridView(clickEventArgs);
        //if (ViewState["SortCPK"].ToString() == sPage)
        //{
        //    if (ViewState["CPKDire"].ToString() == "DESC")
        //        ViewState["CPKDire"] = "ASC";
        //    else
        //        ViewState["CPKDire"] = "DESC";

        //    BindSort("SortCPK", "CPKDire");
        //}

        //if (ViewState["SortUnitsFailed"].ToString() == sPage)
        //{
        //    if (ViewState["UnitsFailedDire"].ToString() == "DESC")
        //        ViewState["UnitsFailedDire"] = "ASC";
        //    else
        //        ViewState["UnitsFailedDire"] = "DESC";
        //    BindSort("SortUnitsFailed", "UnitsFailedDire");
        //}

        //if (ViewState["SortFailedRate"].ToString() == sPage)
        //{
        //    if (ViewState["FailedRateDire"].ToString() == "DESC")
        //        ViewState["FailedRateDire"] = "ASC";
        //    else
        //        ViewState["FailedRateDire"] = "DESC";
        //    BindSort("SortFailedRate","FailedRateDire");
        //}


    }

    private void LoadGridView(string sPage)
    {
        if (ViewState["SortCPK"].ToString() == sPage)
        {
            if (ViewState["CPKDire"].ToString() == "DESC")
                ViewState["CPKDire"] = "ASC";
            else
                ViewState["CPKDire"] = "DESC";

            BindSort("SortCPK", "CPKDire");
        }

        if (ViewState["SortUnitsFailed"].ToString() == sPage)
        {
            if (ViewState["UnitsFailedDire"].ToString() == "DESC")
                ViewState["UnitsFailedDire"] = "ASC";
            else
                ViewState["UnitsFailedDire"] = "DESC";
            BindSort("SortUnitsFailed", "UnitsFailedDire");
        }

        if (ViewState["SortFailedRate"].ToString() == sPage)
        {
            if (ViewState["FailedRateDire"].ToString() == "DESC")
                ViewState["FailedRateDire"] = "ASC";
            else
                ViewState["FailedRateDire"] = "DESC";
            BindSort("SortFailedRate", "FailedRateDire");
        }
    }
    /// <summary>
    /// 判断是否直接点击分页，如果直接点击分页那么就没有排序
    /// </summary>
    private void IsWhichBind()
    {
        if (string.IsNullOrEmpty(clickEventArgs))
        {
            BindSort();
        }
        else
        {
            LoadGridView(clickEventArgs);
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        this.lblCurrentPage.Text = string.Format("当前第{0}页/总共{1}页", this.GridView1.PageIndex + 1, this.GridView1.PageCount);
        //遍历所有行设置边框样式
        foreach (TableCell tc in e.Row.Cells)
        {
            tc.Attributes["style"] = "border-color:Black";
        }
        GridViewRow row = e.Row;
        for (int i = -1; i < GridView1.Rows.Count; i++)
        {
            //判断是否为数据行（排除头部和底部）
            if (row.RowType == DataControlRowType.DataRow)
            {
                double lbl = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "CpkValue"));
                // int lbl = Convert.ToInt32(GridView1.Rows[i].Cells[4].ToString());
                if (lbl < 1.33)
                {
                    e.Row.Cells[2].ForeColor = Color.Red;
                }
                else
                {
                    e.Row.Cells[2].ForeColor = Color.Black;
                }
            }

        }
    }
    /// <summary>
    /// 重新绑定
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
        //BindSort();
        IsWhichBind();
    }
    protected void lnkbtnFrist_Click(object sender, EventArgs e)
    {
        this.GridView1.PageIndex = 0;
        //BindSort();
        IsWhichBind();

    }
    protected void lnkbtnPre_Click(object sender, EventArgs e)
    {
        if (this.GridView1.PageIndex > 0)
        {
            this.GridView1.PageIndex = this.GridView1.PageIndex - 1;
            //  BindSort();
            IsWhichBind();
        }
    }
    protected void lnkbtnNext_Click(object sender, EventArgs e)
    {
        if (this.GridView1.PageIndex < this.GridView1.PageCount)
        {
            this.GridView1.PageIndex = this.GridView1.PageIndex + 1;
            // BindSort();
            IsWhichBind();
        }
    }
    protected void lnkbtnLast_Click(object sender, EventArgs e)
    {
        this.GridView1.PageIndex = this.GridView1.PageCount;
        //BindSort();
        IsWhichBind();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        // Export("application/ms-excel", "整机包装表格.xls");
        Btn_Excel_Click();
    }
    /// <summary>
    /// 定义导出Excel的函数
    /// </summary>
    /// <param name="FileType"></param>
    /// <param name="FileName"></param>
    private void Export(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    /// <summary>
    /// 此方法必重写，否则会出错
    /// </summary>
    /// <param name="control"></param>
    //public override void VerifyRenderingInServerForm(Control control)
    //{
    //}


    protected void Btn_Excel_Click()
    {
        //导出全部数据，取消分页
        GridView1.AllowPaging = false;
        GridView1.ShowFooter = false;
        IsWhichBind();

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "utf-8";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("导出" + System.DateTime.Now.Date.ToString("yyyyMMdd")) + ".xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文

        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
        this.EnableViewState = false;
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

        ClearControls(GridView1);
        this.GridView1.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();

        //还原分页显示
        GridView1.AllowPaging = true;
        GridView1.ShowFooter = true;
        IsWhichBind();
    }

    /// <summary>
    /// GridView如果需要实现导出Excel功能，则该函数需要重载
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for
    }

    /// <summary>
    /// 清除控件中的所有控件，以便导出Excel
    /// </summary>
    /// <param name="control"></param>
    private void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);
        }

        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
                }
                catch
                {
                }
                control.Parent.Controls.Remove(control);
            }
            else if (control.GetType().GetProperty("Text") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                control.Parent.Controls.Remove(control);
            }
        }
        return;
    }
}